# -*- coding: utf-8 -*-

import cgi
import cStringIO as StringIO
import os
import sys

sys.path.insert(0, "%s/../common/zip_packages/reportlab.zip" % os.path.dirname(__file__))
sys.path.insert(0, "%s/../common/zip_packages/html5lib.zip" % os.path.dirname(__file__))
sys.path.insert(0, "%s/../common/zip_packages/pyPdf.zip" % os.path.dirname(__file__))
sys.path.insert(0, "%s/../common/zip_packages/xhtml2pdf.zip" % os.path.dirname(__file__))

import xhtml2pdf.ho.pisa as pisa

from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.template import RequestContext
from ragendja.template import render_to_response, render_to_string

def index(request):
    
    result = StringIO.StringIO()
    html = render_to_string(request, "sample.html", {})
    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)

    if not pdf.err:
        response = HttpResponse(result.getvalue(), mimetype='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=sample.pdf'
        return response
        
    return HttpResponse('We had some errors<pre>%s</pre>' % cgi.escape(html))